package problems.practice;

import java.util.Locale;

/**
 * 2243. 计算字符串的数字和
 * <p>https://leetcode.cn/problems/calculate-digit-sum-of-a-string/</p>
 *
 * @author habitplus
 * @since 21:36, 2022/10/12
 */
public class T2243 {
    public String digitSum(String s, int k) {
        if (s == null || s.length() < 1) return "";

        char[] chs = s.toCharArray();
        int n = chs.length;

        int j;
        int sum;
        char[] tmpChs;

        while (n > k) {
            // 分组计算
            j = 0;
            sum = 0;
            for (int i = 0; i < n; ++i) {
                sum += chs[i] - '0';
                if ((i == n - 1) || (i + 1) % k == 0) {
                    tmpChs = String.valueOf(sum).toCharArray();
                    System.arraycopy(tmpChs, 0, chs, j, tmpChs.length);
                    j += tmpChs.length;
                    sum = 0;
                }
            }
            n = j;
        }

        return String.valueOf(chs, 0, n);
    }
}
